#include "config.h"

bool Config::init(const std::string& file) {
  {
    rwlock::LockWrite _(lock_);
    if (!utility::json_read_file(file, &json_)) {
      std::cout << "[Config] Read config file error!" << std::endl;
      return false;
    }
    file_ = file;
  }

  std::cout << "[Config] Web root is ";
  std::cout << web_root() << std::endl;

  {
    auto af = api_file();
    rwlock::LockWrite _(api_lock_);
    if (!utility::json_read_file(af, &api_)) {
      std::cout << "[Config] Read api file error!" << std::endl;
      return false;
    }
  }
  return true;
}
crow::json::rvalue Config::config() const {
  rwlock::LockRead _(lock_);
  return json_;
}
crow::json::rvalue Config::listen() const {
  rwlock::LockRead _(lock_);
  return json_["listen"];
}
const std::string& Config::web_root() {
  if (root_.empty()) {
    rwlock::LockRead _(lock_);
    root_ = json_["web"]["root"].s();
    check_end_prefix(root_);
    if (root_[0] != '/') {
      auto tmp = utility::file_path(file_) + root_;
      root_.swap(tmp);      
    }
  }
  return root_;
}
const std::string& Config::web_index() {
  if (index_.empty()) {
    index_ = web_root();
    check_end_prefix(index_);
    rwlock::LockRead _(lock_);
    index_ += json_["web"]["index"].s();
  }
  return index_;
}
const std::string& Config::web_api_api_prefix() {
  rwlock::LockRead _(lock_);
  return json_["web"]["api_prefix"].s();
}
const std::string& Config::api_file() {
  if (api_file_.empty()) {
    {
      rwlock::LockRead _(lock_);
      api_file_ = json_["api_file"].s();
    }
    if (api_file_[0] != '/') {
      auto tmp = utility::file_path(file_) + api_file_;
      api_file_.swap(tmp);
    }
  }
  
  return api_file_;
}
crow::json::rvalue Config::api_data() const {
  rwlock::LockRead _(api_lock_);
  return api_["data"];
}
crow::json::rvalue Config::api_apis() const {
  rwlock::LockRead _(api_lock_);
  return api_["apis"];
}
void Config::check_end_prefix(std::string& path) const {
  if (path.empty()) return;
  if (path.at(path.length()-1) != '/')
    path += '/';
}